<?php

namespace app\common\command\Sync;

use app\common\model\yikatong\Employee;
use app\common\model\yikatong\Ysskmj;
use app\common\model\yikatong\Xfcardxf;
use app\common\model\yikatong\Parkcarrecord;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class Yikatong extends Command
{
    protected function configure()
    {
        $this->setName('sync:yikatong')->setDescription('Sync yikatong data');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function execute(Input $input, Output $output)
    {
        //一卡通配置
        $cardConfig = config('database_card');

        //查询所有员工
        $employees = Db::connect($cardConfig)->table('Employee')->select();
        collection($employees)->each(function ($item) {
            $attributes = ['empno' => $item['empno']];
            $values = $item;
            (new Employee())->updateOrCreate($attributes, $values);
        });
        $output->writeln('员工信息同步完成');

        //查询门禁原始刷卡表
        $ysskmjMax =  Ysskmj::max('id') ?: 0;
        $ysskmj = Db::connect($cardConfig)->table('YSSKMJ')->where('id', '>', $ysskmjMax)->select();
        collection($ysskmj)->each(function ($item) {
            $attributes = ['id' => $item['id']];
            $values = $item;
            (new Ysskmj())->updateOrCreate($attributes, $values);
        });
        $output->writeln('门禁信息同步完成');

        //查询刷卡消费表
        $xfcardxfMax =  Xfcardxf::max('id') ?: 0;
        $xfcardxf = Db::connect($cardConfig)->table('XFCardXF')->where('id', '>', $xfcardxfMax)->select();
        collection($xfcardxf)->each(function ($item) {
            $attributes = ['id' => $item['id']];
            $values = $item;
            (new Xfcardxf())->updateOrCreate($attributes, $values);
        });
        $output->writeln('刷卡消费信息同步完成');

        //一卡通配置
        $parkConfig = config('database_park');

        //查询车辆进出记录
        $parkcarrecordMax =  Parkcarrecord::max('id') ?: 0;
        $parkcarrecord = Db::connect($parkConfig)->table('ParkCarRecord')->where('id', '>', $parkcarrecordMax)->select();
        collection($parkcarrecord)->each(function ($item) use ($output) {
            $attributes = ['id' => $item['id']];
            $values = $item;
            (new Parkcarrecord())->updateOrCreate($attributes, $values);
        });
        $output->writeln('车辆进出信息同步完成');
    }
}
